﻿using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Text;
using Microsoft.VisualStudio.TextTemplating;

namespace SharePoint.Orm.Metal.T4 {
	internal class TemplateHost : ITextTemplatingEngineHost {
		private readonly List<string> _standardImports = new List<string>();
		private readonly List<string> _standardAssemblyReferences = new List<string>();
		private readonly Dictionary<string, object> _hostOptions = new Dictionary<string, object>();
		private readonly AppDomain _appDomain;
		public string TemplateFile { get; set; }

		public TemplateHost() {
			_appDomain = AppDomain.CurrentDomain;
			_standardAssemblyReferences.Add(typeof(CodeComment).Assembly.Location);
			_standardImports.Add("System");
			_hostOptions["CacheAssemblies"] = true;
		}

		public bool LoadIncludeText(string requestFileName, out string content, out string location) {
			throw new NotImplementedException();
		}

		public string ResolveAssemblyReference(string assemblyReference) {
			return assemblyReference;
		}

		public Type ResolveDirectiveProcessor(string processorName) {
			if (processorName == "SharePointMetal") {
				return typeof(CustomDirectiveProcessor);
			}
			throw new Exception("Invalid directive processor '" + processorName + "'");
		}

		public string ResolvePath(string path) {
			throw new NotImplementedException();
		}

		public string ResolveParameterValue(string directiveId, string processorName, string parameterName) {
			throw new NotImplementedException();
		}

		public AppDomain ProvideTemplatingAppDomain(string content) {
			return _appDomain;
		}

		public void LogErrors(CompilerErrorCollection errors) {
			if (errors.HasErrors) {
				throw new TemplateException(errors);
			}
		}

		public void SetFileExtension(string extension) {
			// do nothing
		}

		public void SetOutputEncoding(Encoding encoding, bool fromOutputDirective) {
			throw new NotImplementedException();
		}

		public object GetHostOption(string optionName) {
			object val;
			if (_hostOptions.TryGetValue(optionName, out val)) {
				return val;
			}
			return null;
		}

		public IList<string> StandardAssemblyReferences {
			get { return _standardAssemblyReferences; }
		}

		public IList<string> StandardImports {
			get { return _standardImports; }
		}
	}
}
